"""
社交互动序列化器
"""
from rest_framework import serializers
from .models import Post, Comment, Like, PostImage


class PostImageSerializer(serializers.ModelSerializer):
    """动态图片序列化器"""
    
    class Meta:
        model = PostImage
        fields = ('id', 'image', 'created_at')


class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    user_username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = Comment
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')


class PostSerializer(serializers.ModelSerializer):
    """动态序列化器"""
    user_username = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.SerializerMethodField()
    images = PostImageSerializer(many=True, read_only=True)
    post_images = serializers.SerializerMethodField()  # 别名，方便前端使用
    comments_count = serializers.SerializerMethodField()
    likes_count = serializers.SerializerMethodField()
    is_liked = serializers.SerializerMethodField()
    
    class Meta:
        model = Post
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')
    
    def get_user_avatar(self, obj):
        if obj.user.avatar:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.user.avatar.url)
            return obj.user.avatar.url
        return None
    
    def get_post_images(self, obj):
        """获取动态图片列表（别名）"""
        return self.get_images(obj)
    
    def get_images(self, obj):
        """获取动态图片列表"""
        images = obj.post_images.all()
        request = self.context.get('request')
        result = []
        for img in images:
            image_data = {
                'id': img.id,
                'image': img.image.url if img.image else None,
                'created_at': img.created_at
            }
            if request and image_data['image']:
                image_data['image'] = request.build_absolute_uri(img.image.url)
            result.append(image_data)
        return result
    
    def get_comments_count(self, obj):
        return obj.comments.count()
    
    def get_likes_count(self, obj):
        return obj.likes.count()
    
    def get_is_liked(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return obj.likes.filter(user=request.user).exists()
        return False


class LikeSerializer(serializers.ModelSerializer):
    """点赞序列化器"""
    user_username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = Like
        fields = '__all__'
        read_only_fields = ('created_at',)

